package inits

import (
	"context"
	"examination-management/srv/cmd/config"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

func init() {
	InitConfig()
	InitMysql()
	InitRedis()
	//InitNacos()
}
func InitConfig() {
	viper.SetConfigFile("D:\\goWork\\src\\examination-management\\srv\\dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("viper 配置读取失败")
	}
	log.Println("viper 配置读取成功")
	err = viper.Unmarshal(&config.AppConf)
	if err != nil {
		panic("viper 配置解析失败")
	}
	log.Println("viper 配置解析成功", config.AppConf)
}

func InitMysql() {
	AppConf := config.AppConf.Mysql
	var err error
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", AppConf.User, AppConf.Password, AppConf.Host, AppConf.Port, AppConf.DataBase)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("mysql 连接失败")
	}
	log.Println("mysql 连接成功", dsn, config.DB)
}

func InitRedis() {
	AppConf := config.AppConf.Redis
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     AppConf.Addr,     // use default Addr
		Password: AppConf.Password, // no password set
		DB:       AppConf.Db,       // use default DB
	})
	err := config.Rdb.Ping(context.Background()).Err()
	if err != nil {
		panic("redis 连接失败")
	}
	log.Println("redis 连接成功", config.Rdb)
}

//func InitNacos() {
//	AppConf := config.AppConf.Nacos
//	clientConfig := constant.ClientConfig{
//		NamespaceId:         AppConf.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
//		TimeoutMs:           5000,
//		NotLoadCacheAtStart: true,
//		LogDir:              "/tmp/nacos/log",
//		CacheDir:            "/tmp/nacos/cache",
//		LogLevel:            "debug",
//	}
//	serverConfigs := []constant.ServerConfig{
//		{
//			IpAddr:      AppConf.IpAddr,
//			ContextPath: "/nacos",
//			Port:        AppConf.Port,
//			Scheme:      "http",
//		},
//	}
//	// Create config client for dynamic configuration
//	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
//		"serverConfigs": serverConfigs,
//		"clientConfig":  clientConfig,
//	})
//	content, err := configClient.GetConfig(vo.ConfigParam{
//		DataId: AppConf.DataId,
//		Group:  AppConf.Group})
//	if err != nil {
//		panic("nacos 连接失败")
//	}
//	log.Println("nacos 连接成功", content)
//}
